
package org.itboys.mobile.service;

import org.itboys.admin.entity.lasted.SystemDictionary;
import org.itboys.admin.service.lasted.SystemDictionaryService;
import org.itboys.commons.utils.time.TimeUtils;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dao.*;
import org.itboys.mobile.entity.mongo.TianJieMember;
import org.itboys.mobile.entity.mysql.*;
import org.itboys.mobile.service.mongo.web.TianJieMemberService;
import org.itboys.mobile.util.DatetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.security.provider.Sun;

import java.math.BigDecimal;
import java.util.*;

/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：圣代_项目自动任务_权限。
 *
 */

@Service
public class SundayJobService {
	protected Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private TianJieWalletMapper walletMapper;
	@Autowired
	private TianJieWalletReleaseRecordMapper releaseRecordMapper;
	@Autowired
	private TianJieWalletRecordMapper walletRecordMapper;
	@Autowired
	private TianJieWalletBlockMapper walletBlockMapper;
	@Autowired
	private TianJieWalletBlockRecordMapper walletBlockRecordMapper;
	@Autowired
	private SystemDictionaryService dictionaryService;
	@Autowired
	private TianJieMemberService memberService;

	/**
	 * 测试代码
	 */
	public void backWalletBlock(){
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("type",SundayCommonConstants.block_record_type_sale);
		List<TianJieWalletBlockRecord> saleRecords= walletBlockRecordMapper.select(param);
		List<Long> memberIds = new ArrayList<>();
		for(TianJieWalletBlockRecord saleRecord:saleRecords){
			memberIds.add(saleRecord.getMemberId());
		}
		param.clear();
		param.put("memberIds",memberIds);
		List<TianJieWalletBlock> walletBlocks = walletBlockMapper.select(param);
		for(TianJieWalletBlock walletBlock:walletBlocks){
			Double blockNumber=walletBlock.getBlockNumber().doubleValue();
			for(TianJieWalletBlockRecord saleRecord:saleRecords){
				if(saleRecord.getId()>229l&&
						walletBlock.getId().longValue()==saleRecord.getBlockWalletId()){
					blockNumber+=saleRecord.getBlockNumber().doubleValue();
					walletBlockRecordMapper.delete(saleRecord.getId());
				}
			}
			walletBlock.setBlockNumber(new BigDecimal(blockNumber));
			logger.info("------区块链钱包用户ID="+walletBlock.getMemberId()+",误操作数量="+walletBlock.getBlockNumber());
			walletBlockMapper.update(walletBlock);
		}
	}
	/**
	 * 区块链自动根据买入记录卖出
	 */
	@Transactional
	public void autoSaleBlock(){

		//查询区块链买入记录：未生成卖出的，区块链买入记录，需要匹配是否到自动卖出时间
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("type",SundayCommonConstants.block_record_type_buy);
		param.put("isSale",SundayCommonConstants.NO);
		param.put("status",SundayCommonConstants.block_record_status_done);
		List<TianJieWalletBlockRecord> buyRecords= walletBlockRecordMapper.select(param);
		//区块链自动卖出天数(默认)
		Integer blockSaleDay=Integer.valueOf(dictionaryService.getDictionaryByKey2("blockSaleDay").getValue());
		//查询区块链钱包
		List<Long> memberIds = new ArrayList<>();
		for(TianJieWalletBlockRecord buyRecord:buyRecords){
			memberIds.add(buyRecord.getMemberId());
		}
		if(ListUtil.isNull(memberIds))return;
		param.clear();
		param.put("memberIds",memberIds);
		List<TianJieWalletBlock> walletBlocks = walletBlockMapper.select(param);
		//查询对应的用户信息（获取小比特币地址）
		param.clear();
		param.put("id in",memberIds);
		List<TianJieMember> members =memberService.list(param);
		//模拟计算买入记录，自动卖出的时间
		for(TianJieWalletBlockRecord buyRecord:buyRecords){
			//买入记录预计卖出时间
			Date saleTime=null;

			for(TianJieWalletBlock walletBlock:walletBlocks){
				if(buyRecord.getBlockWalletId().longValue()==walletBlock.getId().longValue()){
					//如果区块链钱包没有设置自动卖出时间，读取字典中的自动卖出时间
					if(walletBlock.getSaleDay()==null){
						walletBlock.setSaleDay(blockSaleDay);
					}
					Calendar expectSaleDay = Calendar.getInstance();
					expectSaleDay.setTime(buyRecord.getCt());
					//加上自动卖出的天数
					expectSaleDay.add(Calendar.DAY_OF_YEAR,walletBlock.getSaleDay());
					saleTime=expectSaleDay.getTime();
					break;
				}
			}

			buyRecord.setSaleTime(saleTime);
			logger.info("系统自动卖出-匹配卖出时间-买入记录ID="+buyRecord.getId()+"，买入数量="+buyRecord.getBlockNumber()+",买入时间="+buyRecord.getCreateTime()+",预计卖出时间="+ TimeUtils.formatToTime(buyRecord.getSaleTime()));

		}
		Calendar now = Calendar.getInstance();
		//开始生成卖出计划
		for(TianJieWalletBlockRecord buyRecord:buyRecords){
			//如果预计卖出时间，大于当前时间
			if(buyRecord.getSaleTime()!=null&&
					buyRecord.getSaleTime().getTime()<=now.getTime().getTime()){
				//比特币地址
				String bitAddress="";
				for(TianJieMember member:members){
					if(LongUtil.isNotZreo(buyRecord.getMemberId())&&
							buyRecord.getMemberId().doubleValue()==member.getId()){
						bitAddress=member.getFinanceBitAddress();
						break;
					}
				}
				//修改区块链钱包。扣减区块链持币数量
				for(TianJieWalletBlock walletBlock:walletBlocks){
					if(buyRecord.getBlockWalletId().longValue()==walletBlock.getId().longValue()){
						walletBlock.setBlockNumber(walletBlock.getBlockNumber().subtract(buyRecord.getBlockNumber()));
						walletBlockMapper.update(walletBlock);
						break;
					}
				}
				logger.info("系统自动卖出-写入数据库-买入记录ID="+buyRecord.getId()+"，卖出数量="+buyRecord.getBlockNumber()+",买入时间="+buyRecord.getCreateTime()+",预计卖出时间="+ TimeUtils.formatToTime(buyRecord.getSaleTime()));
				TianJieWalletBlockRecord saleRecord = new TianJieWalletBlockRecord(buyRecord.getMemberId(),buyRecord.getBlockWalletId(),
						buyRecord.getTotalAmount(),buyRecord.getAmount(),buyRecord.getBlockNumber(),
						null,SundayCommonConstants.block_record_type_sale,
						SundayCommonConstants.block_record_status_doing, "系统自动卖出"+buyRecord.getId());
				//新增卖出记录
				walletBlockRecordMapper.insert(saleRecord);
				//修改买入记录，设置为已卖出
				buyRecord.setIsSale(SundayCommonConstants.YES);
				walletBlockRecordMapper.update(buyRecord);
			}
		}
	}
	/**
	 * 释放待释放金额，凌晨3点
	 */
	@Transactional
	public void release(){
		//按释放时间查询所有未释放的充值记录
	//	Date now = new Date();
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("status",SundayCommonConstants.YES);
		param.put("isRelease",SundayCommonConstants.NO);
		param.put("type",SundayCommonConstants.wallet_record_type_charge);
		param.put("releaseTimSmaller", DatetUtil.formatDateToTime(Calendar.getInstance().getTime()));
		//需要释放的钱包交易(充值)记录
		List<TianJieWalletRecord> needToReleaseRecords=  walletRecordMapper.select(param);
		if(ListUtil.isNull(needToReleaseRecords))return;
		//匹配对应的钱包
		List<Long> walletIds = new ArrayList<>();
		for(TianJieWalletRecord needToReleaseRecord:needToReleaseRecords){
			walletIds.add(needToReleaseRecord.getWalletId());
		}
		if(ListUtil.isNull(walletIds))return;
		param.clear();
		param.put("ids",walletIds);
		List<TianJieWallet> wallets = walletMapper.select(param);
		/**
		 * 2017年12月14日，
		 * 如果账户持有的待释放余额小于充值记录中的金额，只释放
		 */
		BigDecimal zero = new BigDecimal("0.00");
		for(TianJieWalletRecord needToReleaseRecord:needToReleaseRecords){
			logger.info("当前充值记录ID-==="+needToReleaseRecord.getId());
			//比较释放记录对应的钱包，如果待释放记录不足。跳过
			boolean isRelease=true;

			for(TianJieWallet wallet:wallets){
				if(LongUtil.isNotZreo(needToReleaseRecord.getWalletId())&&
						needToReleaseRecord.getWalletId()==wallet.getId().longValue()){
					//查询用户待释放金额是否还有钱
					if(wallet.getUnreleaseAmount().compareTo(zero)==1){
						isRelease=true;
						//待释放金额充足，按充值金额释放
						if(needToReleaseRecord.getAmount().compareTo(wallet.getUnreleaseAmount())!=1){
							//
							wallet.setUnreleaseAmount(wallet.getUnreleaseAmount().subtract(needToReleaseRecord.getAmount()));
							wallet.setReleaseAmount(wallet.getReleaseAmount().add(needToReleaseRecord.getAmount()));
							//待释放金额不足，按剩余待释放余额释放
						}else{
							//扣减钱包待释放
							wallet.setUnreleaseAmount(zero);
							//增加已释放金额
							wallet.setReleaseAmount(wallet.getReleaseAmount().add(wallet.getUnreleaseAmount()));
						}
						walletMapper.update(wallet);
					}


					break;
				}
			}
			if(isRelease){
				//修改充值记录
				needToReleaseRecord.setIsRelease(SundayCommonConstants.YES);
				logger.info("-----修改的待释放记录"+needToReleaseRecord.getId()+"计划释放时间="+DatetUtil.formatDateToTime(needToReleaseRecord.getReleaseTime()));
				walletRecordMapper.update(needToReleaseRecord);
				//新增钱包交易记录
				walletRecordMapper.insert(new TianJieWalletRecord(needToReleaseRecord.getMemberId(), needToReleaseRecord.getWalletId(), SundayCommonConstants.wallet_record_type_release, "待释放金额释放"+needToReleaseRecord.getId(),needToReleaseRecord.getAbleAmount(), needToReleaseRecord.getAmount(), SundayCommonConstants.YES));
			}
		}
	}
}